﻿using Autofac;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using AutofacModel = Autofac.Module;

namespace ThresholdAssistant.Autofac
{
    /// <summary>
    /// Autofac属性注入扩展
    /// </summary>
    public static class AutofacInjection
    {
        /// <summary>
        /// 添加属性注入
        /// </summary>
        /// <param name="services"></param>
        public static void AddAutofac(this IServiceCollection services)
        {
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //说明：ConfigureServices返回IServiceProvider，通过接口属性来获取,自动获取Controller的属性
            services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
        }
        
        /// <summary>
        /// 使用属性注入
        /// </summary>
        /// <param name="builder"></param>
        public static void UseAutofac(this ContainerBuilder builder)
        {
            builder.RegisterModule<DefaultModule>();//使用属性注入
        }

        /// <summary>
        /// 使用属性注入
        /// </summary>
        /// <param name="builder"></param>
        public static void UseAutofac<T>(this ContainerBuilder builder) where T : AutofacModel, new()
        {
            builder.RegisterModule<T>();//使用属性注入
        }

        /// <summary>
        /// 使用Atofac服务
        /// </summary>
        /// <param name="host"></param>
        public static IHost UseAutofacService(this IHost host)
        {
            AutofacProvider.ServiceProvider = host.Services;
            return host;
        }
    }
}